package com.guochenglang.www.controller;

import com.guochenglang.www.pojo.User;
import com.guochenglang.www.service.SearchService;
import com.guochenglang.www.service.UserService;
import com.guochenglang.www.util.GetObject;
import com.guochenglang.www.util.MyDependency;
import com.guochenglang.www.util.PatternUtil;
import com.guochenglang.www.util.jwts.JwtUtils;
import com.guochenglang.www.web.result.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 用户Controller层
 *
 * @author GuoChenglang
 */

public class UserController {
    private static final UserService USER_SERVICE = MyDependency.returnObject(UserService.class);
    private static final SearchService SEARCH_SERVICE = MyDependency.returnObject(SearchService.class);

    /**
     * 获得用户信息
     */
    public static Result getUser(HttpServletRequest request, HttpServletResponse response) throws SQLException, InterruptedException, IllegalAccessException, InstantiationException {
        //获得用户id
        int id = Integer.parseInt(request.getParameter("userId"));
        return Result.result(USER_SERVICE.getUser(id));
    }

    /**
     * 修改用户信息
     */
    public static Result updateUser(HttpServletRequest request, HttpServletResponse response) throws SQLException, InterruptedException, IllegalAccessException, IOException, InstantiationException {
        //获得用户id
        Integer userId = GetObject.getValue(request, Integer.class, "userId");
        //获得邮箱
        String email = GetObject.getValue(request, String.class, "email");
        //获得电话
        String phone = GetObject.getValue(request, String.class, "phone");
        //判断邮箱是否合法
        if (!PatternUtil.isRealEmail(email)) {
            Result result = Result.noResult();
            result.setMsg("email");
            return result;
        } else if (!PatternUtil.isPhone(phone)) {
            //判断手机号是否合法
            Result result = Result.noResult();
            result.setMsg("phone");
            return result;
        }
        int num = USER_SERVICE.updateUser(userId, new User(null, null, phone, email, null, null));
        return Result.result(num);

    }

    /**
     * 登录
     */
    public static Result logIn(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException, InterruptedException, IllegalAccessException, InstantiationException, NoSuchAlgorithmException {
        //获得用户信息
        String username = GetObject.getValue(req, String.class, "username");
        String password = GetObject.getValue(req, String.class, "password");
        String define = GetObject.getValue(req, String.class, "define");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        //验证验证码并比较
        String code = req.getSession().getAttribute("code").toString();
        if (!code.equalsIgnoreCase(define)) {
            return Result.error("worseCode");
        }
        //获得用户键值对
        HashMap<String, Object> data = GetObject.getObject(req, HashMap.class);
        //获得session
        HttpSession session = req.getSession();
        //搜索用户
        User select = USER_SERVICE.logIn(user);
        if (select != null) {
            //登录成功，获得jwt令牌并存进session里
            String jwt = JwtUtils.getJwt(data);
            session.setAttribute("user", jwt);
            return Result.result(select);
        } else {
            //登录失败
            return Result.noResult();
        }

    }

    /**
     * 注册
     */
    public static Result signIn(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException, InterruptedException, IllegalAccessException, NoSuchAlgorithmException, InstantiationException {
        //封装前端表单数据
        String username = GetObject.getValue(req, String.class, "username");
        String password = GetObject.getValue(req, String.class, "password");
        String email = GetObject.getValue(req, String.class, "email");
        //获得验证码与域中的验证码进行比较
        String code = GetObject.getValue(req, String.class, "code");
        User aUser = new User(null, null, null, email, username, password);
        String realCode = req.getSession().getAttribute("code").toString();
        if (!realCode.equalsIgnoreCase(code)) {
            return Result.noResult();
        }
        int key = USER_SERVICE.signIn(aUser);
        if (key < 0) {
            return Result.error("repeat");
        }
        return Result.result(key);

    }

    /**
     * 找回密码
     */
    public static Result recover(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException, InterruptedException, IllegalAccessException, InstantiationException, NoSuchAlgorithmException {
        String username = GetObject.getValue(req, String.class, "username");
        String password = GetObject.getValue(req, String.class, "password");
        String code = GetObject.getValue(req, String.class, "code");
        //检验验证码
        String define = req.getSession().getAttribute("code").toString();
        if (!define.equalsIgnoreCase(code)) {
            return Result.noResult();
        }
        int num = USER_SERVICE.changePassword(password, username);
        return Result.result(num);
    }

    /**
     * 退出登录
     */
    public static Result logOut(HttpServletRequest req, HttpServletResponse resp) {
        //移除令牌
        req.getSession().removeAttribute("user");
        return Result.result();
    }

    /**
     * 用户搜索
     */
    public static Result searchUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException, InterruptedException, IllegalAccessException, InstantiationException, NoSuchAlgorithmException {
        String keyword = req.getParameter("input");
        ArrayList<User> users = SEARCH_SERVICE.userSearch(keyword);
        return Result.result(users);
    }
}
